//
//  IssueViewController.swift
//  Git@OSC
//
//  Created by AeternChan on 9/22/15.
//  Copyright © 2015 oschina. All rights reserved.
//

import UIKit
import WebKit

class IssueViewController: UITableViewController, WKNavigationDelegate, UIWebViewDelegate {
    
    var viewModel: IssueViewModel!
    
    var webViewHeight: Float = 44
    
    @IBOutlet weak var statusLabel: UILabel!
    @IBOutlet weak var titleLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.title = "#\(viewModel.issue.iid)"
        
//        tableView.estimatedRowHeight = 200
//        tableView.rowHeight = UITableViewAutomaticDimension
        
        viewModel.page.producer
            .filter { $0 > 0 }
            .start {
                data in
                    self.tableView.reloadData()
            }
        
        viewModel.fetchNotes()
        
        if viewModel.issue.state == "closed" {
            statusLabel.textColor = UIColor(rgba:"#BD2C00")
            statusLabel.text = Octicons.IssueClosed.rawValue
        } else {
            statusLabel.textColor = UIColor(rgba: "#6CC644")
            statusLabel.text = Octicons.IssueOpened.rawValue
        }
        
        titleLabel.text = viewModel.issue.title
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return viewModel.notes.count > 0 ? 2 : 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return section == 0 ? 2 : viewModel.notes.count
    }
    
    override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return section == 0 ? nil : "评论"
    }
    
    override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 44
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.section == 0 && indexPath.row == 1 {
            return CGFloat(webViewHeight)
        } else {
            return UITableViewAutomaticDimension
        }
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        switch indexPath.section {
        case 0:
            if indexPath.row == 0 {
                let cell = tableView.dequeueReusableCellWithIdentifier("AuthorInfo", forIndexPath: indexPath) as! AuthorInfoCell
                cell.setContent(viewModel.issue.author.avatarURL!, info: "\(viewModel.issue.author.name) - \(viewModel.issue.createdAt.prettify())")
                
                return cell
            } else {
                let cell = tableView.dequeueReusableCellWithIdentifier("Detail", forIndexPath: indexPath) as! WebViewCell
                cell.html = viewModel.issue.issueDescription
//                cell.webView.navigationDelegate = self
                cell.webView.delegate = self
                cell.webView.scrollView.scrollEnabled = false
                
                return cell
            }
        default:
            let cell = tableView.dequeueReusableCellWithIdentifier("Note", forIndexPath: indexPath) as! NoteCell
            cell.entity = viewModel.notes[indexPath.row]
            
            return cell
        }
    }
    
    
    // MARK: - WKNavigationDelegate
    
//    func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
//        
//        let height = Float(webView.stringByEvaluatingJavaScriptFromString("document.body.offsetHeight")!)
//        if webViewHeight != height {
//            webViewHeight = height!
//            tableView.reloadData()
//        }
//    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        let height = Float(webView.stringByEvaluatingJavaScriptFromString("document.body.offsetHeight;")!)! + 30
        
        if webViewHeight != height {
            webViewHeight = height
            tableView.beginUpdates()
            tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 1, inSection: 0)], withRowAnimation: .Automatic)
            tableView.endUpdates()
        }
    }


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
